<script lang="ts" setup>
import { Rules } from 'async-validator'
import { provide, ref } from 'vue'
import { FormItem, key } from '../../types/form.type'
import mitter from '../../util/mitter'

defineOptions({
  name: 'SForm',
})

const props = defineProps<{ model: Record<string, unknown>; rules: Rules }>()

const formItem = ref<FormItem[]>([])

provide(key, { model: props.model, rules: props.rules })

mitter.on('addFormItem', (item: FormItem) => {
  formItem.value.push(item)
})

const validator = (callback: (isValidator: boolean) => void) => {
  const tacks = formItem.value.map((item) => item.validator())

  Promise.all(tacks)
    .then(() => {
      callback(true)
    })
    .catch(() => {
      callback(false)
    })
}

defineExpose({ validator })
</script>

<template>
  <div class="S-form">
    <slot />
  </div>
</template>
